<template>
  <div class="user-list p-8 bg-white rounded-lg shadow-md max-w-4xl mx-auto">
    <h2 class="text-2xl font-bold mb-6 text-center">用户列表</h2>

    <!-- 查询输入框 -->
    <div class="search-container mb-6">
      <input
        v-model="queryId"
        @input="searchUsersById"
        placeholder="请输入用户ID进行搜索"
        class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:border-blue-500"
      />
    </div>

    <div v-if="loading" class="text-center mb-6">
      <p class="text-gray-600">Loading users...</p>
    </div>

    <div v-else-if="error" class="text-center mb-6">
      <p class="text-red-500">{{ error }}</p>
      <button
        @click="fetchUsers"
        class="mt-2 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
      >
        重试
      </button>
    </div>

    <div v-else-if="users.length === 0" class="text-center mb-6">
      <p class="text-gray-600">未找到用户，请尝试添加新用户。</p>
    </div>

    <table v-else class="w-full border-collapse">
      <thead class="bg-gray-100">
        <tr>
          <th class="px-4 py-2 text-left">编码ID</th>
          <th class="px-4 py-2 text-left">用户名</th>
          <th class="px-4 py-2 text-left">邮箱地址</th>
          <th class="px-4 py-2 text-left">电话</th>
          <th class="px-4 py-2 text-left">性别</th>
          <th class="px-4 py-2 text-left">生日</th>
          <th class="px-4 py-2 text-left">备注</th>
          <th class="px-4 py-2 text-left">操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id" class="hover:bg-gray-50">
          <td class="px-4 py-2 border-t">{{ user.id }}</td>
          <td class="px-4 py-2 border-t">{{ user.userName }}</td>
          <td class="px-4 py-2 border-t">{{ user.email }}</td>
          <td class="px-4 py-2 border-t">{{ user.phone }}</td>
          <td class="px-4 py-2 border-t">
            <span v-if="user.gender === 'male'">男</span>
            <span v-else-if="user.gender === 'female'">女</span>
            <span v-else>{{ user.gender }}</span>
          </td>
          <td class="px-4 py-2 border-t">{{ formatBirthday(user.birthday) }}</td>
          <td class="px-4 py-2 border-t">{{ user.note }}</td>
          <td class="px-4 py-2 border-t">
            <div class="flex space-x-2">
              <router-link :to="`/edit/${user.id}`" class="text-blue-500 hover:text-blue-700">
                编辑
              </router-link>
              <button
                @click="deleteUser(user.id)"
                class="text-red-500 hover:text-red-700"
                :disabled="deleting"
              >
                {{ deleting ? '删除中...' : '删除' }}
              </button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
// 这里代码不变，同你原始代码中的script部分
import { ref, onMounted, watch } from 'vue'
import { UserService } from '@/services/userService'
import { useRouter } from 'vue-router'

const users = ref([])
const loading = ref(true)
const error = ref(null)
const deleting = ref(false)
const queryId = ref('') // 查询条件字段（用户ID）
const router = useRouter()

// 格式化生日字段
const formatBirthday = (birthday) => {
  if (!birthday) return ''
  const date = new Date(birthday)
  return date.toLocaleDateString()
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  error.value = null
  try {
    users.value = await UserService.getAllUsers()
    loading.value = false
  } catch (err) {
    error.value =
      err.response?.data?.message || 'Failed to fetch users. Please check your connection.'
    loading.value = false
  }
}

// 根据用户ID查询用户
const searchUsersById = async () => {
  loading.value = true
  error.value = null
  try {
    if (!queryId.value.trim()) {
      // 如果没有输入查询条件，获取所有用户
      await fetchUsers()
    } else {
      // 根据ID查询用户
      const id = parseInt(queryId.value.trim(), 10)
      if (isNaN(id)) {
        error.value = '请输入有效的用户ID'
        users.value = []
      } else {
        const user = await UserService.getUserById(id)
        users.value = user ? [user] : [] // 将用户放入数组中以便统一渲染
      }
    }
    loading.value = false
  } catch (err) {
    error.value =
      err.response?.data?.message || 'Failed to fetch user. Please check your connection.'
    loading.value = false
  }
}

// 删除用户
const deleteUser = async (id) => {
  if (confirm('是否确认删除当前用户?')) {
    deleting.value = true
    try {
      await UserService.deleteUser(id)
      users.value = users.value.filter((user) => user.id !== id)
    } catch (err) {
      error.value = err.response?.data?.message || 'Failed to delete user'
    } finally {
      deleting.value = false
    }
  }
}

onMounted(fetchUsers)

// 监听路由变化，更新用户列表
watch(
  () => router.currentRoute.value.state,
  (newState) => {
    if (newState && newState.updatedUser) {
      const updatedUser = newState.updatedUser
      const index = users.value.findIndex((user) => user.id === updatedUser.id)
      if (index !== -1) {
        users.value[index] = updatedUser
      }
    }
  },
  { deep: true },
)
</script>
